package com.automannn.tomcat.practice.springWeb.webStarter;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenkh
 * @time 2021/10/13 13:45
 */
/*xxx: 注意，当容器中，注册了 HandlerAdapter，以及HandlerMapping时，将会打乱默认的SpringMvc行为*/
@Component
public class AutomanHandlerMapping implements HandlerMapping {
    @Override
    public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        String beanName =  request.getParameter("beanName");

        if (!StringUtils.isEmpty(beanName)){
            HandlerExecutionChain handlerExecutionChain = new HandlerExecutionChain("automan");
            handlerExecutionChain.addInterceptor(new HandlerInterceptor() {
                @Override
                public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                    System.out.println("前置拦截。");
                    return true;
                }

                @Override
                public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                    System.out.println("后置拦截。");
                }

                @Override
                public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                    System.out.println("完成后拦截。");
                }
            });
            return handlerExecutionChain;
        }else{
            return null;
        }

    }
}
